<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 2017/8/1
 * Time: 下午4:16
 */

namespace app\controllers;

use app\librarys\ApiResponseCode;
use app\librarys\BaseApiController;
use app\models\Ad;
use app\models\Group;
use app\models\User;
use app\models\Merchant;
use app\models\Sms;
use app\librarys\MobilePhoneAreaQuery;
use app\librarys\RegeoSdk;

/**
 * 用户端Api接口。需要用户登录后使用
 * @package app\controllers
 */
class ApiUserController extends BaseApiController
{
    private $currentUser = null;
    private $arr = array();

    public function beforeAction($action)
    {
//        $this->currentUser = User::getCurrentUser();
//        if ($this->currentUser == null) {
//            echo $this->renderJson(null, ApiResponseCode::UserSessionErrorCode, ApiResponseCode::UserSessionErrorMessage);
//            return false;
//        }


        if (self::IsFormRequest == true) {
            $this->_request = \Yii::$app->request;
        } else {
            $this->_request = json_decode(file_get_contents("php://input"));
        }

        $token = $this->_getRequestValue('user_token');
        $userId = User::authUserToken($token);
//        $userId = 'aeec08bb-d27e-11e7-aa8f-00163e06b8e1';
        $user = User::getById($userId);

        if ($user == null) {
            echo $this->renderJson(null, ApiResponseCode::UserSessionErrorCode, ApiResponseCode::UserSessionErrorMessage);
            return false;
        } else {
            User::setCurrentUser($user);
        }

        return parent::beforeAction($action);
    }


    /**
     * 编辑用户个人资料
     * @return string
     */
    public function actionSaveUserInfo()
    {
        $name = $this->_getRequestValue('name');
        $nick_name = $this->_getRequestValue('nick_name', '');
        $phone = $this->_getRequestValue('phone', '');
        $gravatar = $this->_getRequestValue('gravatar', '');
        $gender = $this->_getRequestValue('gender', 1);
        $birthday = $this->_getRequestValue('birthday', null);
        $occupation = $this->_getRequestValue('occupation', '');
        $company = $this->_getRequestValue('company', '');
        $school = $this->_getRequestValue('school', '');
        $hobby = $this->_getRequestValue('hobby', '');
        $tag = $this->_getRequestValue('tag', '');

        $user_id = User::getCurrentUser()['id'];

        $result = User::save($user_id, $name, $nick_name, $phone, $gravatar, $gender, $birthday, $occupation, $company, $school, $hobby, $tag);
        return $this->renderJson(null, $result ? 0 : 1, $result ? 'success' : 'fail');
    }

    /**
     * 获取个人资料
     * @return string
     */
    public function actionGetUserInfo()
    {
        $user_id = User::getCurrentUser()['id'];
        $item = User::getById($user_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail' : 'success');

    }

    /**
     * 更新用户位置信息
     */
    public function actionSetUserPosition()
    {
        $user_id = User::getCurrentUser()['id'];
        $lon = $this->_getRequestValue('lon');
        $lat = $this->_getRequestValue('lat');
        $item = User::setUserPosition($user_id, $lon, $lat);
        self::actionUpdateUserTourist($user_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '未发生更改' : 'success');

    }

    /**
     * 更新用户是否是游客
     */
    public function actionUpdateUserTourist($user_id)
    {
            $user = User::getUser($user_id);
//            var_dump($user);

            $phone_area = MobilePhoneAreaQuery::query($user['phone']);

//            var_dump($phone_area);
            $area = RegeoSdk::getArea($user['lon'],$user['lat']);
            if($area==null || $area=='' || $area == -1 || $phone_area ==-1)
                return;
//            var_dump($area['array']);
//            var_dump($area.' xx  '.$phone_area);
            if(!strstr($area,$phone_area))
            {//游客
                User::updateTourist($user['id'],1);
            }else{
                User::updateTourist($user['id'],0);

            }
    }

    /**
     * 获取广告详情
     * @return string
     */
    public function actionGetAd()
    {
//        $user_id = User::getCurrentUser()['id'];
        $ad_id = $this->_getRequestValue('ad_id');
        $items['ad'] = User::getAd($ad_id);
        $items['urls'] = Ad::getAdImages($ad_id);
//        $items['ad'] = $items['0'];
//        $items['0'] = null;
        return $this->renderJson($items, is_null($items) ? 1 : 0, is_null($items) ? 'fail' : 'success');

    }

    /**
     * 添加分享记录
     */
    public function actionAddShareRecord()
    {
        $user_id = User::getCurrentUser()['id'];
        $ad_id = $this->_getRequestValue('ad_id');
        $share_type = $this->_getRequestValue('share_type');
        $item = AD::addShareRecord($ad_id,$user_id,$share_type);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail' : 'success');
    }

    /**
     * 根据位置查询附近广告
     */
    public function actionGetAdByArea()
    {
        $user_id = User::getCurrentUser()['id'];
        $lon = $this->_getRequestValue('lon');
        $lat = $this->_getRequestValue('lat');
        $search_range = $this->_getRequestValue('search_range');

        $item = User::getAdsByArea($user_id, $lon, $lat, $search_range);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '未发生更改' : 'success');

    }

    /**
     * 获取红包领取次数
     * @param $ad_id
     */
    public function actionGetReadTimes()
    {
        $ad_id = $this->_getRequestValue('ad_id');
        $item = User::getGiftTimes($ad_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'ad_id无效' : 'success');
    }

    /**
     * 收藏商家
     * @param $merchant_id
     */
    public function actionKeepMerchant()
    {
        $merchant_id = $this->_getRequestValue('merchant_id');
        $user_id = User::getCurrentUser()['id'];
        $item = User::keepMerchant($user_id, $merchant_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '已经收藏' : 'success');
    }

    /**
     * 收藏广告
     */
    public function actionKeepAd()
    {
        $ad_id = $this->_getRequestValue('ad_id');
        $user_id = User::getCurrentUser()['id'];
        $item = User::keepAd($user_id, $ad_id);
        return $this->renderJson($item,  0, is_null($item) ? 'success' : 'success');

    }

    /**
     * 举报广告
     */
    public function actionAccuseAd()
    {
        $ad_id = $this->_getRequestValue('ad_id');
        $user_id = User::getCurrentUser()['id'];
        User::accuseAd($user_id, $ad_id);
        return $this->renderJson();
    }

    /**
     * 返回红包口令
     * @param $ad_id
     * @return string
     */
    public function actionGetWord()
    {
        $ad_id = $this->_getRequestValue('ad_id');
        $item = User::getWord($ad_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'ad_id无效' : 'success');
    }

    /**
     * 返回指定红包领取状态
     */
    public function actionGetCashGiftStatus()
    {
        $ad_id = $this->_getRequestValue('ad_id');
        $user_id = User::getCurrentUser()['id'];

        $item = User::getGiftCash($ad_id, $user_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'ad_id无效' : 'success');
    }

    /**
     * 获取商家详情
     * @return string
     */
    public function actionGetMerchantInfo()
    {
        $merchant_id = $this->_getRequestValue('merchant_id');
        $item = User::getMerchat($merchant_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'merchant_id无效' : 'success');
    }

    /**
     * 获取总红包收入
     */
    public function actionGetTotal()
    {
        $user_id = User::getCurrentUser()['id'];
        $item = User::getTotalGift($user_id);
        //var_dump($item);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '当前用户为零' : 'success');
    }

    /**
     * 返回用户的红包，包括广告名称、广告图片
     */
    public function actionGetMyGiftList()
    {
        $user_id = User::getCurrentUser()['id'];

        $item = User::getMyGiftList($user_id);

        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '当前用户为零' : 'success');

//        $item['ad_images'] = Ad::getAdImages('ad_id');//这个就是广告的图片
//        foreach ($item['ad_images'] as &$ad_image){//这样便利，加了&这个符号的话就会修改遍历的单项
//            $ad_image = 2;
//        }
    }

    /**
     * 领取红包
     * @return string
     */
    public function actionGetGift()
    {
        $user_id = User::getCurrentUser()['id'];
        $ad_id = $this->_getRequestValue('ad_id');
        $word = $this->_getRequestValue('word');


        $item = User::getGift($user_id, $ad_id,$word);
        $message = '';
        // var_dump('item:'.$item);
        if ($item['status'] == 1) {
            $message = 'success';
        } elseif ($item['status'] == 2) {
            $message = '红包领过了,或者没有接到推送';
        } elseif ($item['status'] == 3) {
            $message = '红包领完了';
        }elseif($item['status'] == 4) {
            $message = '回答错误！';
        }elseif($item['status'] == 5) {
            $message = '只能回答一次哟，没有机会拉！';
        }
        return $this->renderJson($item, $item['status'], $message ? $message : 'success');
    }

    /**
     * 更新用户资料
     */
    public function actionUpdateUser()
    {
        $user_id = User::getCurrentUser()['id'];
        $gravatar = $this->_getRequestValue('gravatar');
        $nick_name = $this->_getRequestValue('nick_name');
        $gender = $this->_getRequestValue('gender');
        $birthday = $this->_getRequestValue('birthday');
        $occupation = $this->_getRequestValue('occupation');
        $company = $this->_getRequestValue('company',' ');
        $school = $this->_getRequestValue('school');
        $hobby = $this->_getRequestValue('hobby');
        $tag = $this->_getRequestValue('tag');

        $item = User::updateUser($user_id, $nick_name, $gravatar, $gender, $birthday, $occupation, $company, $school, $hobby, $tag);

        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'id error' : 'success');
    }

    /**
     * 获取收藏的广告
     */
    public function actionGetAdFollowList()
    {
        $userId = User::getCurrentUser()['id'];
        $page = $this->_getRequestValue('page', 0);
        $pageSize = $this->_getRequestValue('page_size', 10);

        $items = User::getAdFollowList($page, $pageSize, $userId);
        foreach ($items as &$item) {
//            var_dump($item);
            $item['count'] = Ad::getAdGotCountById($item['id']);
        }
        return $this->renderJson($items);
    }

    /**
     * 获取收藏的商户
     * @return string
     */
    public function actionGetMerchantFollowList()
    {
        $userId = User::getCurrentUser()['id'];
        $page = $this->_getRequestValue('page', 0);
        $pageSize = $this->_getRequestValue('page_size', 10);

        $items = User::getMerchantFollowList($page, $pageSize, $userId);
        return $this->renderJson($items);
    }

    /**
     * 意见反馈
     * @return string
     */
    public function actionFeedback()
    {
        $userId = User::getCurrentUser()['id'];
        $feedback = $this->_getRequestValue('feedback');

        $id = User::feedback($userId, $feedback);
        return $this->renderJson($id);
    }

    /**
     * 获取group列表
     * @return string
     */
    public function actionGetGroups()
    {
        $items = Group::getList(0, PHP_INT_MAX);
        return $this->renderJson($items);
    }

    public function actionGetMyGroups()
    {
        $userId = User::getCurrentUser()['id'];
        $item = User::getMygroupList($userId);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '没有加入任何平台' : 'success');
    }

    /**
     * 申请group
     */
    public function actionApplyGroup()
    {
        $group_id = $this->_getRequestValue('group_id');
        $user_id = User::getCurrentUser()['id'];
        $user_name = $this->_getRequestValue('user_name');
        $user_phone = $this->_getRequestValue('user_phone');

        $id = Group::saveGroupUserAuth($user_id, $user_name, $user_phone, $group_id);

        return $this->renderJson($id, empty($id) ? 1 : 0, empty($id) ? '申请失败' : '申请成功');
    }

    /**
     * 获取系统消息
     */
    public function actionGetMessages()
    {
//        $merchant_id = Merchant::getCurrentMerchant()['id'];

        $page = $this->_getRequestValue('page',0);
        $pageSize = $this->_getRequestValue('page_size',20);
        $item = Merchant::getMessages(2,$page,$pageSize);

        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '没有消息拉!' : 'success');

    }

    /**
     * 设置／更新提现密码
     */
    public function actionSetMoneyPassword()
    {
        $userId = User::getCurrentUser()['id'];
        $phone = User::getById($userId)['phone'];

                $verify_word = $this->_getRequestValue('verify_word');

        $auth = Sms::authSmsVerificationCode($phone, $verify_word);
        if ($auth == false) {
            return $this->renderJson(null, ApiResponseCode::SmsVerificationCodeAuthFailedErrorCode, ApiResponseCode::SmsVerificationCodeAuthFailedErrorMessage);
        }
        $password = $this->_getRequestValue('password');
        $item = User::setMoneyPassword($userId,$password);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');

    }

    /**
     * 提交提现申请
     * @return string
     */
    public function actionApplyWishdrawCash()
    {
        $userId = User::getCurrentUser()['id'];
        $wishType = $this->_getRequestValue('wish_type');
        $cash = $this->_getRequestValue('cash');
        $passwd = $this->_getRequestValue('password');
        $account = $this->_getRequestValue('account');
//        $verify_word = $this->_getRequestValue('verify_word');
//
//        $auth = Sms::authSmsVerificationCode($phone, $verify_word);
//        if ($auth == false) {
//            return $this->renderJson(null, ApiResponseCode::SmsVerificationCodeAuthFailedErrorCode, ApiResponseCode::SmsVerificationCodeAuthFailedErrorMessage);
//        }

        $item = null;
        //判断密码
        if(!User::verifyPassword($passwd,$userId))
        {
            //密码错
            return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '密码错!' : 'success');
        }

        $temp = User::queryUserMoeny($userId);
//        var_dump('余额'.$temp."cash".$cash);
        if($temp<$cash)
        {
            //余额不足
            return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '余额不足!' : 'success');

        }

       $item = User::applyWishdrawCash($userId,$wishType,$cash,$account);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? '提现请求失败!' : 'success');

    }

    /**
     * 获取用户昵称和头像
     * @return string
     */
    public function actionGetNames()
    {
        $userId = User::getCurrentUser()['id'];
        $item = User::getUserNames($userId);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');
    }

    /**
     * 绑定推送ID
     * @return string
     */
    public function actionBandPushId()
    {
        $userId = User::getCurrentUser()['id'];
        $push_id = $this->_getRequestValue('push_id');
        $item = User::bandPushId($userId,$push_id);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');
    }

    /**
     * 获取用户信息
     * @return string
     */
    public function actionGetUser()
    {
        $userId = User::getCurrentUser()['id'];
        $item = User::getUser($userId);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');
    }

    /**
     * 添加广告图片
     */
    public function actionAddAdData()
    {
//        User::addAdData();
    }

    /**
     * 记录分享成功
     */
    public function actionRecordShare()
    {
        $userId = User::getCurrentUser()['id'];
        $title = $this->_getRequestValue('title','');
        $share_type = $this->_getRequestValue('share_type');

        $item = User::addShareRecord($userId,$title,$share_type);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');

    }

    /**
     * 设置用户临时标签
     * @return string
     */
    public function actionSetTags()
    {
        $userId = User::getCurrentUser()['id'];
        $tags = $this->_getRequestValue('tags');
        $t1 = '';
       foreach ($tags as $tag)
       {
          $t1 .= $tag.' ';
       }

       $item = User::updateTags($userId,$t1);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');

    }

    /**
     * 设置用户个人爱好
     * @return string
     */
    public function actionSetHobbys()
    {
        $userId = User::getCurrentUser()['id'];
        $hobbys = $this->_getRequestValue('hobbys');
        $t1 = '';
        foreach ($hobbys as $hobby)
        {
            $t1 .= $hobby.' ';
        }

        $item = User::updateHobbys($userId,$t1);
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');

    }

    /**
     * 返回所有groups
     * @return string
     */
    public function actionGetAllGroups()
    {
        $item  = Group::getAll();
        return $this->renderJson($item, is_null($item) ? 1 : 0, is_null($item) ? 'fail!' : 'success');

    }

}